from flask import request,session,json,render_template
from application.events import events
from db_util.models import db,Events,Colleague
from sqlalchemy import and_
import time

#######################################
#         定义接口：日程模块
#######################################

#日程新增
@events.route("/events/events_add",methods=['GET','POST'])
def events_add():
    data = request.get_data("data")
    data = bytes.decode(data)
    if(len(data)>0):
        data = json.loads(data)

    events = Events()
    events.user_id = session["user_id"]
    events.text = data['title']
    events.start_date = data['sdate']
    events.end_date = data['edate']
    events.level = data['level']
    db.session.add(events)
    db.session.commit()
    db.session.close();
    return("新建日程成功！")

#日程修改
@events.route("/events/events_update",methods=['GET','POST'])
def events_update():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)

    print(data);
    user_id = session["user_id"]
    text = data['title']
    start_date = data['sdate']
    end_date = data['edate']
    level = data['level']
    oldTitle = data['oldTitle']
    oldStart = data['oldStart']
    oldEnd = data['oldEnd']
    if(start_date == end_date):
        end_day = end_date.split();
        end_daytime = end_day[0];
        end_time = time.strftime('%H:%M:%S',time.localtime(time.time()));
        end_date = end_daytime+" "+end_time;
    sql = 'select * from events where text = :text and start_date = :start_date and end_date = :end_date';
    events = db.session.execute(sql, {'text': oldTitle, 'start_date': oldStart,
                                      'end_date': oldEnd}).first()
    id = events.id;
    # 如果当前ID和用户ID不一致，说明是好友在操作。判断权限
    if (session['user_id'] != events.user_id):
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == events.user_id, Colleague.colleague_id == session['user_id'])).first();
        if (colleague.permission == 0):
            return ("无权限操作！");
    db.session.execute('update events set start_date = :startdate,end_date=:enddate,text=:text,level = :level where id=:id',
                       {'startdate':start_date,'enddate':end_date,'text':text,'level':level,'id':id})
    db.session.commit()
    db.session.close();
    return ("修改成功")

#日程查看
@events.route("/events/events_info",methods=['GET','POST'])
def events_info():
    return

#日程列表
@events.route("/events/events_list",methods=['GET','POST'])
def events_list():
    user_id = session["user_id"]
    events_list = db.session.query(Events).filter(Events.user_id == user_id).all()
    res = "["
    i = 0;
    for item in events_list:
        if i != 0:
            res = res + ","
        if item.level == 0:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\""+str(item.id)+"\",\"color\":\"blue\"}";
        elif item.level ==1:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\"" + str(item.id) + "\",\"color\":\"orange\"}";
        else:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"red\"}";
        i=i+1
        res = res + item_str;
        print(i);
    res = res + "]"
    events_list = json.dumps(res)
    db.session.close();
    return events_list

#日程删除
@events.route("/events/events_delete",methods=['GET','POST'])
def events_delete():
    data = request.get_data("data")
    data = bytes.decode(data)
    if (len(data) > 0):
        data = json.loads(data)
    user_id = session["user_id"]
    text = data['title']
    start_date = data['sdate']
    end_date = data['edate']

    # 多条件查询
    sql = 'select * from events where text = :text and start_date = :start_date and end_date = :end_date';
    events = db.session.execute(sql, {'text': text, 'start_date': start_date,
                                      'end_date': end_date}).first();
    #如果当前ID和用户ID不一致，说明是好友在操作。判断权限
    if(session['user_id']!=events.user_id):
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == session['user_id'], Colleague.colleague_id == events.user_id)).first();
        if(colleague.permission == 0):
            return("无权限操作！");
    db.session.execute('delete from events where id=:id',{'id':events.id})
    db.session.commit()
    db.session.close();
    return ("删除成功！")

